<template>
  <view
    class="content-cavansindex"
    @click="topsharecloes"
    @touchmove.stop.prevent="() => {}"
  >
    <view>
      <canvas
        ref="canvasindex"
        canvas-id="posterCanvas"
        class="canvas-imgs"
        :style="{ width: cw + 'px', height: ch + 'px' }"
      ></canvas>
    </view>
    <view
      class="content-index"
      :style="{ marginBottom: showbt ? '120rpx' : '0rpx' }"
      v-if="imageurl"
      :class="show ? 'content-index-show' : ''"
      @click.stop
    >
      <image
        class="img-canvas"
        @load="imageload"
        :src="imageurl"
        mode="widthFix"
      ></image>
      <!-- #ifdef H5 -->
      <view class="item-dec"> 长按图片保存/分享 </view>
      <!-- #endif -->
    </view>

    <!-- #ifdef APP-PLUS -->
    <view class="content-bt" v-if="imageurl" @click.stop="() => {}">
      <view class="canvas-bt-in" @click="sharesare"> 保存图片 </view>
    </view>
    <!-- #endif -->

    <view class="content-bt" v-if="showbt">
      <view class="canvas-bt-in" @click="sharecloes"> 取消 </view>
    </view>
  </view>

  <!-- canvas-id="posterCanvas" -->
</template>

<script setup>
import { nextTick, ref, onMounted, getCurrentInstance } from "vue";

// 获得当前组件实例
const instance = getCurrentInstance();

const emit = defineEmits(["cloesEvent"]);

const propss = defineProps({
  showbt: {
    type: Boolean,
    default(rawProps) {
      return false;
    },
  },
  bgimg: {
    type: Object,
    default(rawProps) {
      return {
        url: "",
        w: 710,
        h: 710,
        l: 20,
        t: 100,
      };
    },
  },
  codeimg: {
    type: Object,
    default(rawProps) {
      return {
        url: "",
        w: 186,
        h: 186,
        l: 544,
        t: 830,
      };
    },
  },
  logo: {
    type: Object,
    default(rawProps) {
      return {
        url: "",
        l: 20,
        t: 20,
        w: 216,
        h: 68,
      };
    },
  },
  titlename: {
    type: Object,
    default(rawProps) {
      return {
        name: "",
        l: 20,
        t: 894,
        size: 54,
        color: "black",
      };
    },
  },
  money: {
    type: Object,
    default(rawProps) {
      return {
        name: "",
        l: 60,
        t: 984,
        size: 54,
        color: "#B63434",
      };
    },
  },

  logoname: {
    type: Object,
    default(rawProps) {
      return {
        name: "",
        l: 476,
        t: 60,
        size: 24,
        color: "#9E9E9E",
      };
    },
  },

  btneme: {
    type: Object,
    default(rawProps) {
      return {
        name: "",
        l: 20,
        t: 1104,
        size: 30,
        color: "#666666",
      };
    },
  },
  cw: {
    type: Number,
    default(rawProps) {
      return 750;
    },
  },
  ch: {
    type: Number,
    default(rawProps) {
      return 1100;
    },
  },
});

const canvasId = "posterCanvas";
const text = "欢迎来到我的世界";
const imageurl = ref("");
const dateobj = ref(propss);

const canvasindex = ref(null);

// 将 canvasToTempFilePath 封装成一个返回 Promise 的函数

// #ifdef MP-WEIXIN
function canvasToTempFilePath() {
  return new Promise(async (resolve, reject) => {
    await uni.canvasToTempFilePath(
      {
        canvasId: "posterCanvas",
        // canvasId: canvasId,
        fileType: "jpg",

        quality: 1,
        success: function (res) {
          imageurl.value = res.tempFilePath;
          uni.hideLoading();
          resolve(res.tempFilePath);
          // uni.hideLoading();
          // emit('childEvent', urlindex.value);
        },
        fail: function (e) {
          // emit('childEvent', "");
          uni.hideLoading();
          reject(e);
        },
      },
      instance
    );
  });
}
// #endif
// #ifdef H5 || APP-PLUS
function canvasToTempFilePath() {
  return new Promise(async (resolve, reject) => {
    await uni.canvasToTempFilePath(
      {
        canvasId: "posterCanvas",
        // canvasId: canvasId,
        fileType: "jpg",

        quality: 1,
        success: function (res) {
          imageurl.value = res.tempFilePath;
          uni.hideLoading();
          resolve(res.tempFilePath);
          // uni.hideLoading();
          // emit('childEvent', urlindex.value);
        },
        fail: function (e) {
          // emit('childEvent', "");
          uni.hideLoading();
          reject(e);
        },
      },
      instance
    );
  });
}
// #endif

async function useCanvasPoster(canvasId, dateobj) {
  uni.showLoading({
    title: "生成中...",
  });

  let imgUrl = dateobj.bgimg; //网络资源背景图片
  let posterQrCodeImg = dateobj.codeimg; //二维码
  let logo = dateobj.logo;
  let logoname = dateobj.logoname;
  let userName = dateobj.titlename;
  let money = dateobj.money;
  let btneme = dateobj.btneme.name;
  let ctx;
  // #ifdef H5 || APP-PLUS

  ctx = uni.createCanvasContext(canvasId);
  // #endif

  // #ifdef MP-WEIXIN
  ctx = uni.createCanvasContext(canvasId, instance);
  // #endif

  async function drawPoster() {
    ctx.setFillStyle("#ffffff");
    ctx.fillRect(0, 0, propss.cw, propss.ch); // 绘制背景
    if (userName && userName.name) {
      let userNames =
        userName.name.length > 6
          ? userName.name.substring(0, 12) + "..."
          : userName.name;
      ctx.setFillStyle(userName.color);
      ctx.setFontSize(userName.size);
      ctx.fillText(userNames, userName.l, userName.t); // 绘制文本
      ctx.draw(true);
    }

    if (logoname && logoname.name) {
      ctx.setFontSize(logoname.size);
      //字体颜色
      ctx.setFillStyle(logoname.color);
      ctx.fillText(logoname.name, logoname.l, logoname.t);
      ctx.draw(true);
    }

    if (money && money.name) {
      ctx.setFillStyle(money.color);
      ctx.setFontSize(money.size);
      ctx.fillText(money.name, money.l, money.t); // 绘制文本
      //字体颜色
      ctx.setFontSize(34);
      ctx.setFillStyle("#B63434");
      ctx.fillText("￥ ", 20, money.t);
      ctx.draw(true);
    }

    if (btneme) {
      ctx.setFontSize(dateobj.btneme.size);
      //字体颜色
      ctx.setFillStyle(dateobj.btneme.color);
      btneme =
        dateobj.btneme.name.length > 40
          ? dateobj.btneme.name.substring(0, 42) + "..."
          : dateobj.btneme.name;
      ctx.lineWidth = 1;
      var str = btneme;
      var lineWidth = 0;
      var canvasWidth = 710; //计算canvas的宽度
      var initHeight = 15; //绘制字体距离canvas顶部初始的高度
      var lastSubStrIndex = 0; //每次开始截取的字符串的索引

      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), 20, dateobj.btneme.t); //绘制截取部分
          initHeight += 40; //20为字体的高度
          lineWidth = 0;
          lastSubStrIndex = i;
        }
        if (i == str.length - 1) {
          //绘制剩余部分  debugger

          ctx.fillText(
            str.substring(lastSubStrIndex, i + 1),
            20,
            (dateobj.btneme.t += dateobj.btneme.size + 10)
          );
        }
      }
    }
    let imgurl = "";
    let temp = null;
    let temp2 = null;
    let temp3 = null;
    // return;

    try {
      if (imgUrl.url) {
        temp = await drawImagefun(ctx, canvasId, imgUrl);
      }
      if (posterQrCodeImg.url) {
        temp2 = await drawImagefun(ctx, canvasId, posterQrCodeImg);
      }
      if (logo.url) {
        temp3 = await drawImagefun(ctx, canvasId, logo);
      }

      ctx.draw(true, () => {
        imgurl = canvasToTempFilePath();
      });
    } catch (e) {
      uni.hideLoading();
    }
    return imgurl;
    // 这里可以添加更多的绘制逻辑，比如绘制图片、绘制边框等
  }

  let temp2 = await drawPoster();

  return temp2;
}

function drawImagefun(ctx, canvasId, obj) {
  if (obj) {
    return new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: obj.url,
        success: async (res) => {
          ctx.drawImage(
            res.path,
            obj && obj.l,
            obj && obj.t,
            obj && obj.w,
            obj && obj.h
          );
          resolve(res);
        },
      });
    }, instance);
  }
}

const show = ref(false);
const imageload = () => {
  show.value = true;
};

const sharecloes = () => {
  emit("cloesEvent");
};
const topsharecloes = () => {
  if (!propss.showbt) {
    emit("cloesEvent");
  }
};
const sharesare = () => {
  uni.showLoading({
    title: "保存中",
    mask: true,
  });
  uni.saveImageToPhotosAlbum({
    filePath: imageurl.value,
    success: function (res) {
      uni.hideLoading();
      uni.showToast({
        title: "保存成功",
        icon: "none",
      });
      emit("cloesEvent");
    },
  });
};

onMounted(() => {
  nextTick(async () => {
    let res;
    // #ifdef H5 || APP-PLUS
    res = await useCanvasPoster(canvasId, dateobj.value);
    // #endif
    // #ifdef MP-WEIXIN
    res = await useCanvasPoster(canvasId, dateobj.value);
    // #endif
  });
});
// on
</script>
<style lang="scss" scoped>
.images {
  width: 750rpx;
  height: 1200rpx;
}

.canvas-imgs {
  position: absolute;
  top: -15000rpx;
  // opacity: 0;
}

.item-dec {
  font-weight: 400;
  font-size: 24rpx;
  color: #666666;
  line-height: 36rpx;
  text-align: center;
  margin-top: 20rpx;
  padding-bottom: 20rpx;
}

.content-cavansindex {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  z-index: 999;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);

  .content-bt {
    width: 100%;
    position: fixed;
    height: 160rpx;
    bottom: 0;
    left: 0;
    background-color: #ffffff;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .canvas-bt-in {
      width: 662rpx;
      height: 72rpx;
      background: #f6f6f6;
      border-radius: 744rpx 744rpx 744rpx 744rpx;
      margin: 30rpx auto 0;
      text-align: center;
      line-height: 72rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: bold;
      font-size: 24rpx;
      color: #444444;
      font-style: normal;
      text-transform: none;
    }
  }

  .content-index {
    width: 600rpx;
    height: auto;
    margin: 0 auto;
    background-color: #ffffff;
    border-radius: 15rpx;
    overflow: hidden;
    opacity: 0;
    margin-bottom: 180rpx;
  }

  .content-index-show {
    opacity: 1 !important;
  }

  .img-canvas {
    width: 100%;
  }
}
</style>
